export class GameOfLife {
  constructor(width, height) {
    this.width = width
    this.height = height
    this.grid = this.createGrid()
  }
  
  // 创建空网格
  createGrid() {
    return Array(this.height).fill().map(() => Array(this.width).fill(false))
  }
  
  // 随机初始化网格
  randomize() {
    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        this.grid[y][x] = Math.random() > 0.85
      }
    }
  }
  
  // 计算下一个世代
  nextGeneration() {
    const newGrid = this.createGrid()
    
    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        const neighbors = this.countNeighbors(x, y)
        const isAlive = this.grid[y][x]
        
        // 应用康威生命游戏规则
        if (isAlive) {
          newGrid[y][x] = neighbors === 2 || neighbors === 3
        } else {
          newGrid[y][x] = neighbors === 3
        }
      }
    }
    
    this.grid = newGrid
  }
  
  // 计算周围活细胞数量
  countNeighbors(x, y) {
    let count = 0
    
    for (let dy = -1; dy <= 1; dy++) {
      for (let dx = -1; dx <= 1; dx++) {
        if (dx === 0 && dy === 0) continue
        
        const newX = x + dx
        const newY = y + dy
        
        if (
          newX >= 0 && 
          newX < this.width && 
          newY >= 0 && 
          newY < this.height &&
          this.grid[newY][newX]
        ) {
          count++
        }
      }
    }
    
    return count
  }
  
  // 获取网格状态
  getGrid() {
    return this.grid
  }
  
  // 设置网格状态
  setGrid(grid) {
    this.grid = grid
  }
} 